import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
import { Modal } from "bootstrap";
export default {
    name: "CoachInfo",
    data() {
        return {
            coachInfo: [],
            searchValue: '',
            newCoach: {
                username: '',
                sex: '',
                age: '',
                id_code: '',
                address: '',
                tel: '',
                sellpoint: '',
                time: '',
            },
        };
    },
    created: function() {
        this.fetchCoaches();
    },

    methods: {
        //转换时间格式
        formatDateTime(dateString) {
            let date = new Date(dateString);
            let year = date.getFullYear();
            let month = String(date.getMonth() + 1).padStart(2, '0');
            let day = String(date.getDate()).padStart(2, '0');

            let hours = String(date.getHours()).padStart(2, '0');
            let minutes = String(date.getMinutes()).padStart(2, '0');
            let seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },

    //显示教练信息
    async fetchCoaches() {
        try {
            const url = "http://localhost:8081/coach/list";
            const response = await axios.get(url);

            this.coachInfo = response.data.data.map(coach => {
                // 检查 coach.image 是否为空，并设置默认图片（请使用适当的默认图片地址替换）
                const imagePath = coach.image ? coach.image.replace(/^D:.*image/, '/image') : '/path/to/default/image.png';
                console.log(imagePath);
                // 将 coach.time 转换为所需的格式
                const formattedTime = this.formatDateTime(coach.time);
                return {
                    ...coach,
                    image: imagePath,
                    time: formattedTime, // 使用格式化的时间替换原始时间
                };
            });
        } catch (error) {
            console.error("Fetching coaches error:", error);
        }
    },
        // 添加新教练
        async addCoach() {
            try {
                const url = "http://localhost:8081/coach/add";

                const response = await axios.post(url, this.newCoach);
                // If adding a coach is successful, close the modal and refresh the coach list
                if (response.data.code === 20000) {
                    const addCoachModal = Modal.getInstance(document.getElementById("addCoachModal"));
                    addCoachModal.hide();
                    this.resetNewCoachData();
                    this.$message.success("添加教练成功！");
                    this.fetchCoaches();
                } else {
                    // If adding a coach fails, display an error message or perform other actions
                    this.$message.error("Adding coach failed:", response.data.message);
                }
            } catch (error) {
                console.error("Adding coach error:", error);
            }
        },

        // 重置添加教练模态框的数据
        resetNewCoachData() {
            this.newCoach = {
                username: "",
                sex: "",
                age: "",
                id_code: "",
                address: "",
                tel: "",
                sellpoint: "",
                time: "",
            };
        },
        // 删除教练
        async deleteCoach(coach) {
            try {
                if (confirm("确认删除该教练？")) {
                    const url = `http://localhost:8081/coach/delete/${coach.id}`;
                    const response = await axios.delete(url);

                    // 如果删除成功，刷新教练列表并显示成功消息
                    if (response.data.code === 20000) {
                        this.fetchCoaches();
                        this.$message.success("删除教练成功！");
                    } else {
                        // 若删除失败，显示错误信息或执行其他操作
                        this.$message.error(`删除教练失败：${response.data.message}`);
                    }
                }
            } catch (error) {
                console.error("Deleting coach error:", error);
            }
        },
        // 保存编辑后的教练信息
        async saveEditedCoach(coach) {
            try {
                const url = `http://localhost:8081/coach/update/${coach.id}`;
                const dateObject = new Date(coach.time);
                coach.time = dateObject.toISOString();
                const response = await axios.put(url, coach);

                // 如果更新成功，刷新教练列表并显示成功消息，取消编辑状态
                if (response.data.code === 20000) {
                    this.fetchCoaches();
                    this.$message.success("编辑教练成功！");
                    coach.editing = false;
                } else {
                    // 若更新失败，显示错误信息或执行其他操作
                    this.$message.error(`编辑教练失败：${response.data.message}`);
                }
            } catch (error) {
                console.error("Saving edited coach error:", error);
            }
        },
        // 上传头像
        getComputedID(coach) {
            return `upload-image-btn-${coach.id}`;
        },
        // 上传头像的方法
        async handleFileUpload(event, coach) {
            try {
                // 获取上传的文件
                const file = event.target.files[0];

                // 使用 FormData 传递文件数据
                const formData = new FormData();
                formData.append("image", file);

                // 发送 POST 请求上传头像
                const url = `http://localhost:8081/coach/uploadImage/${coach.id}`;
                const response = await axios.post(url, formData, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                });

                // 如果上传成功，更新 coach.image，显示成功消息
                if (response.data.code === 20000) {
                    coach.image = response.data.data.image; // 更新 coach.image 的值（确保将 image 替换为服务器返回的图片 URL）
                    this.fetchCoaches();
                    this.$message.success("上传头像成功！");
                } else {
                    // 若上传失败，显示错误信息或执行其他操作
                    this.$message.error(`上传头像失败：${response.data.message}`);
                }
            } catch (error) {
                console.error("Uploading image error:", error);
            }
        },
    //查询教练
        async search() {
            try {
                const url = `http://localhost:8081/coach/search/${this.searchValue}`;
                const response = await axios.get(url);

                if (response.data.code === 20000) {
                    const imagePath = response.data.data.image.replace(/^D:.*image/, '/image');
                    this.coachInfo = [
                        {
                            ...response.data.data,
                            image: imagePath,
                        },
                    ];
                    this.searchValue = '';
                    this.$message.success("查询成功！");
                } else {
                    this.searchValue = '';
                    this.$message.error(`查询出错：${response.data.message}`);
                }
            } catch (error) {
                console.error("Searching error:", error);
                alert("搜索教练出错，请检查输入的ID和网络连接。");
            }
        },


    },
};